import ajax from "../business/ajax";
import list from "../views/list.art";

function listInit(res, userList) {
  let page = 0;
  let userNames = [];
  let passWord = [];
  let len;
  let i = 0;
  $(document).on("click", (e) => changePageHandler(e));
  $(document).on("delete", deleteHandler);
  if (!userList) return;
  userList.forEach((item) => {
    userNames[i] ? "" : (userNames[i] = []);
    passWord[i] ? "" : (passWord[i] = []);
    userNames[i].push(item.accountName);
    passWord[i].push(item.passWord);
    if (userNames[i].length === 5) i++;
  });
  len = new Array(userNames.length).fill(0);
  res.render(list([userNames[page], len, passWord[page]]));
  function changePageHandler(e) {
    if (e.target.nodeName === "A") {
      switch (e.target.innerText) {
        case "«":
          page--;
          break;
        case "»":
          page++;
          break;
        default:
          page = Number(e.target.innerText) - 1;
          break;
      }
      page = page <= 0 ? 0 : page;
      page = page >= len.length - 1 ? len.length - 1 : page;
      res.render(list([userNames[page], len, passWord[page]]));
    }
    if (e.target.innerText === "删除") {
      ajax("delete", { data: e.target.dataset["id"] }, "json");
    }
  }
  function deleteHandler(e, newList) {
    newList = newList.userList;
    if (!newList) return;
    userNames = [];
    passWord = [];
    i = 0;
    newList.forEach((item) => {
      userNames[i] ? "" : (userNames[i] = []);
      passWord[i] ? "" : (passWord[i] = []);
      userNames[i].push(item.accountName);
      passWord[i].push(item.passWord);
      if (userNames[i].length === 5) i++;
    });
    len = new Array(userNames.length).fill(0);
    res.render(list([userNames[page], len, passWord[page]]));
  }
}

export default listInit;
